//  this library.
import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hktk_app/dao/subject_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/practice/ct_enum.dart';
import 'package:hktk_app/ienum/question/answer_type_enum.dart';
import 'package:hktk_app/ienum/question/collect_type_enum.dart';
import 'package:hktk_app/ienum/question/question_type_enum.dart';
import 'package:hktk_app/ienum/subject/collection_type_enum.dart';
import 'package:hktk_app/model/data_model.dart';
import 'package:hktk_app/model/practice/practice_question_model.dart';
import 'package:hktk_app/model/question/paper_data_model.dart';
import 'package:hktk_app/model/question/question_data_model.dart';
import 'package:hktk_app/model/subject/question_collection_model.dart';
import 'package:hktk_app/pages/question/child/question_exam_page.dart';
import 'package:hktk_app/pages/question/child/question_page.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/my_util.dart';

/// 章节对应做题页面
class ChapterQuestionPage extends StatefulWidget {
  /// 对应id，记录id
  final String id;

  /// 对应的试卷/章节/记录id
  final String cId;

  /// 对应的试题类型
  final CtEnum rType;

  /// 对应请求类型
  final CollectionTypeEnum collType;

  /// 栏目id
  final String columnId;

  /// 是练习模式还是考试模式，true：练习模式，false：考试模式
  final bool practice;

  /// 考试时间
  final int examTime;

  const ChapterQuestionPage({
    super.key,
    required this.id,
    required this.collType,
    required this.columnId,
    required this.cId,
    required this.rType,
    this.practice = true,
    this.examTime = 0,
  });

  @override
  State<ChapterQuestionPage> createState() => _ChapterQuestionPageState();
}

class _ChapterQuestionPageState extends State<ChapterQuestionPage> {
  /// 试题集合
  late Map<String, QuestionDataModel> _dataMap;

  @override
  Widget build(BuildContext context) {
    if (widget.practice) {
      return QuestionPage(paperInit: _initData, quesInit: _quesInit);
    } else {
      return QuestionExamPage(
        paperInit: _initData,
        quesInit: _quesInit,
        type: QuestionTypeEnum.exam,
      );
    }
  }

  /// 加载数据方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      DataModel dataModel = dataUtilComm.dataModel;
      QuestionCollectionModel model = await SubjectDao.questionCollection(
        collectionTypeEnum: widget.collType,
        industryCode: dataModel.industryId,
        examId: dataModel.examId,
        categoryId: dataModel.categoryId,
        columnId: widget.columnId,
        id: widget.id,
        trueV: widget.practice,
      );
      PaperDataModel paperDataModel = _getPaperData(model);
      map["data"] = paperDataModel;
      map["suc"] = true;
    } catch (e) {
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 获取对应的试题数据方法
  PaperDataModel _getPaperData(QuestionCollectionModel model) {
    List<DtkInfoModel> dtkList = [];
    List<BogInfoModel> bogList = [];
    _dataMap = {};
    List<ContentCollection> content = model.content!;
    int ii = 0;
    int index = 0;
    for (int i = 0; i < content.length; i++) {
      ContentCollection collection = content[i];
      bogList.add(BogInfoModel(
        name: collection.tyName!,
        type: collection.qs![0].firstType!,
        total: collection.qs?.length ?? 0,
        dtkList: [],
      ));
      List<PracticeQuestionModel> qsList = collection.qs!;
      for (int j = 0; j < qsList.length; j++) {
        PracticeQuestionModel qModel = qsList[j];
        // 试题数据
        QuestionDataModel qDataModel = MyUtil.getQuestionData(qModel);
        _dataMap[qModel.id!] = qDataModel;
        if (model.lastId == qModel.id) {
          index = ii;
        }
        // 收藏
        CollectTypeEnum type = CollectTypeEnum.def;
        if (qModel.collect != null && qModel.collect!) {
          type = CollectTypeEnum.suc;
        }
        // 本题是否已做
        AnswerTypeEnum ansType = AnswerTypeEnum.notDone;
        List<String> ans = [];
        if (qModel.record != null) {
          RecordModel record = qModel.record!;
          if (widget.rType == CtEnum.paperRecordPaperLibrary) {
            ansType = AnswerTypeEnum.success;
          } else {
            ansType =
            record.rt! ? AnswerTypeEnum.success : AnswerTypeEnum.error;
          }
          ans = MyUtil.getUserAnsList(record.as, qModel.firstType!);
        }

        // 答题卡相关数据
        dtkList.add(DtkInfoModel(
          index: ii,
          id: qModel.id!,
          type: qModel.firstType!,
          sign: qModel.sign!,
          collType: type,
          ansType: ansType,
          answerBase64: qModel.answerBase64,
          st: qDataModel.stem,
          userAns: ans,
        ));
        ii++;
      }
    }
    return PaperDataModel(
      name: model.name!,
      id: model.id!,
      collectId: widget.cId,
      lastIndex: index,
      dtkList: dtkList,
      bogDtkList: bogList,
      rType: widget.rType,
      examTime: widget.examTime,
      startDate: DateTime.now().millisecondsSinceEpoch,
    );
  }

  /// 加载试题数据方法
  Future<Map<String, dynamic>> _quesInit(String qId, String cid) async {
    QuestionDataModel? dataModel = _dataMap[qId];
    if (dataModel == null) {
      return {"suc": false, "msg": "未知错误，请重试"};
    }
    return {"suc": true, "data": dataModel};
  }
}
